from rest_framework.views import APIView
from rest_framework.response import Response
import os
from django.conf import settings
from django.core.cache import cache

class PictureListView(APIView):
    directory = ''

    def dispatch(self, request, *args, **kwargs):  #将wsgi的request封装，返回rest_framework的request对象
        self.directory = kwargs.pop('directory', '')
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        pictures_dir = os.path.join(settings.STATICFILES_DIRS[0], 'images', self.directory)  # 构造图片目录路径
        picture_files = os.listdir(pictures_dir)    # 获取目录中的所有文件名
        picture_files.sort()  # 确保顺序一致

        cache_key = f'current_picture_index_{self.directory}'  # 构建缓存键，用于存储当前目录的图片索引
        current_index = cache.get(cache_key, 0)
        if current_index >= len(picture_files):
            current_index = 0

        picture_url = os.path.join(settings.STATIC_URL, 'images', self.directory, picture_files[current_index])
        cache.set(cache_key, current_index + 1)

        return Response({"url": picture_url})  # 返回包含图片URL的响应